﻿#region using statements
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Data;
using System.Web;
using System.Web.UI.WebControls;
using System.Text;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

using Microsoft.Office.Word.Server.Service;
using Microsoft.Office.Word.Server.Conversions;
#endregion

namespace WordServicesUIExtensions
{
    public partial class SubmitConversion : LayoutsPageBase
    {
        void AddSelectItem(DVDropDownList ddl)
        {
            ListItem selectItem = new ListItem("[Select]", String.Empty);
            ddl.Items.Insert(0, selectItem);
        }
        protected void DataBindDropDowns()
        {
            string[] tokens = Enum.GetNames(typeof(SaveFormat));
            documentTypesDropDownList.DataSource = tokens;
            documentTypesDropDownList.DataBind();
            AddSelectItem(documentTypesDropDownList);

            foreach (SPList list in SPContext.Current.Web.Lists)
            {
                if (list.BaseType == SPBaseType.DocumentLibrary && list.BaseTemplate == SPListTemplateType.DocumentLibrary)
                {
                    ListItem item = new ListItem(list.Title, list.Title);
                    outputLibraryDropDownList.Items.Add(item);
                }
            }
            AddSelectItem(outputLibraryDropDownList);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //databind the dropdowns
                DataBindDropDowns();

            }
        }
        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            try
            {
                string saveFormatAsString = documentTypesDropDownList.SelectedValue ;
                if (String.IsNullOrEmpty(saveFormatAsString)) return;
                string selectedIds = Request.QueryString["SelectedItems"];
                if (String.IsNullOrEmpty(selectedIds)) return;
                selectedIds = selectedIds.Substring(0, selectedIds.Length - 1);
                string sourceList = Request.QueryString["SourceList"];
                if (String.IsNullOrEmpty(sourceList)) return;

                SaveFormat saveFormat = (SaveFormat)Enum.Parse(typeof(SaveFormat), saveFormatAsString);
                string[] tokens = selectedIds.Split("|".ToCharArray());
                Submit(new Guid(sourceList), saveFormat, tokens);
 
                if (this.IsDialogMode)
                {
                    //generate client side script to close the dialog window
                    this.additionalPageHeadLiteral.Text = "<script type='text/javascript'>window.frameElement.commitPopup();</script>";
                }
            }
            catch (Exception ex)
            {
                //TODO:Log
                Response.Redirect("/_layouts/Error.aspx?ErrorText=" + Server.UrlEncode(ex.Message));
            }
        }

        void Submit(Guid sourceListGuid, SaveFormat saveFormat, string[] selectedIds)
        {
            ConversionJobSettings jobSettings = new ConversionJobSettings();
            jobSettings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;
            jobSettings.OutputFormat = saveFormat;

            WordServiceApplicationProxy proxy = (WordServiceApplicationProxy)SPServiceContext.Current.GetDefaultProxy(typeof(WordServiceApplicationProxy));
            ConversionJob conversionJob = new ConversionJob(proxy, jobSettings);
            conversionJob.Name = jobNameTextBox.Text;
            //set user token & Site Subscription Ids
            conversionJob.UserToken = SPContext.Current.Web.CurrentUser.UserToken;
            if(SPContext.Current.Site.SiteSubscription != null)
                conversionJob.SubscriptionId = SPContext.Current.Site.SiteSubscription.Id;

            if (selectedIds.Length > 0)
            {
                SPList theList = SPContext.Current.Web.Lists[sourceListGuid];
                if (theList != null)
                {
                    foreach (string id in selectedIds)
                    {
                        //add files
                        SPListItem item = theList.Items.GetItemById(Convert.ToInt32(id));
                        string fileUrl = SPContext.Current.Web.Url + "/" + item.Url;
                        //only process docx files
                        if (Path.GetExtension(fileUrl).ToLower() == ".docx")
                        {
                            conversionJob.AddFile(fileUrl, Path.ChangeExtension(fileUrl, GetExtension(saveFormat)));
                        }
                    }                    
                    if(outputLibraryDropDownList.SelectedItem.Value != string.Empty)
                    {
                        SPList outLibrary = SPContext.Current.Web.Lists[outputLibraryDropDownList.SelectedItem.Value];
                        //Specify conversion job where to output the converted documents
                        conversionJob.AddLibrary(theList, outLibrary);
                    }
                }
                //start the job
                conversionJob.Start();
            }
        }
        string GetExtension(SaveFormat saveFormat)
        {
            string rc = string.Empty ;

            switch (saveFormat)
            {
                case SaveFormat.PDF:
                    rc = "PDF" ;
                    break;
                case SaveFormat.RTF:
                    rc = "RTF";
                    break;
                case SaveFormat.XML:
                    rc = "XML";
                    break;
                case SaveFormat.XPS:
                    rc = "XPS";
                    break;
                case SaveFormat.MHTML:
                    rc = "mhtml";
                    break;
            }

            return rc ;
        }
    }
}
